import asyncio
import functools
import time
from datetime import datetime

import requests

from src.allview.allviews import AllViews
from src.common.constant import BACKSTAGE_URL


async def run(value):
    status_msg = "推送成功"
    try:
        print(value.get("wpName", ""))
        allview = AllViews()
        # allview.login()
        wp_id, wp_type = await allview.add_action(**value)
        judges = value.get("judges")
        batch_from_judge = [batch for batch in value.get("batchs", "")]
        await allview.wp_params_save(*[wp_id], **value)
        for judge in judges:
            sales_rmd = judge.get("salesRmd", "")
            j_id = await allview.add_sales_rmd(*[wp_id, wp_type], **judge)
            batch_to_posts = list(filter(lambda batch: batch["salesRmd"] == sales_rmd, batch_from_judge))
            batch_to_posts = [] if batch_to_posts is None else batch_to_posts
            for batch in batch_to_posts:
                await allview.wp_batch_save(*[wp_id, j_id], **batch)
        records = value.get("records", [])
        for record in records:
            await allview.wp_record_save(*[wp_id], **record)
    # #     # return "success", "推送成功"
    except Exception as error:
        print(error)
        del error
        status_msg = "推送失败"
    finally:
        from src.singletone.error_msg_singleton import ErrorMsg
        print(ErrorMsg().error_msg)
        return ErrorMsg().error_msg, status_msg


def push_msg(item_id, features):
    p_msg, p_status = features.result()
    responses = requests.post(BACKSTAGE_URL["push_result"], data={"id": item_id,
                                                                  "pushMsg": p_msg,
                                                                  "pushStatus": p_status,
                                                                  "pushTime":
                                                                      datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                                                  })

    print(responses.text)
    pass


def start():
    response = requests.get(BACKSTAGE_URL["load_json"])
    result = response.json()
    start_time = time.time()
    # loop = asyncio.get_event_loop()
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    tasks = []
    for item in result["po"]:
        feature = asyncio.ensure_future(run(item))
        feature.add_done_callback(functools.partial(push_msg, item["id"]))
        tasks.append(feature)
    if any(tasks):
        loop.run_until_complete(asyncio.wait(tasks))
    print("{} task run in {}s:".format(len(tasks), time.time() - start_time))


if __name__ == '__main__':
    # print(ErrorMsg().error_msg)
    start()
    # scheduler = AsyncIOScheduler()
    # scheduler.add_job(start, trigger="interval", seconds=30)
    # try:
    #     scheduler.start()
    #     asyncio.get_event_loop().run_forever()
    # except Exception as e:
    #     print(str(e))
    #     scheduler.shutdown()
    # while True:
    #     start()
    #     time.sleep(30)
